package com.salton123.ads.provider

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Application
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.MobileAds
import com.google.android.gms.ads.OnUserEarnedRewardListener
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import com.google.android.gms.ads.rewarded.RewardItem
import com.google.android.gms.ads.rewarded.RewardedAd
import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback
import com.salton123.log
import com.salton123.provider.AbsRevenueProvider
import com.salton123.utils.task.ThreadQueue

/**
 * Time:2022/3/10 10:34 上午
 * Author:
 * Description:
 */
@SuppressLint("MissingPermission")
class AdMobProvider(application: Application) : AbsRevenueProvider(application) {
    companion object {
        private const val tag = "AdMobProvider"
        private const val GOOGLE_REWARD_ID = "ca-app-pub-2524044598927030/7070579303"
        //test
//        private const val GOOGLE_REWARD_ID = "ca-app-pub-3940256099942544/5224354917"
    }

    override fun init(application: Application) {
        super.init(application)
        log(tag, "init")
        MobileAds.initialize(application) {
            val sb = StringBuffer()
            it.adapterStatusMap.forEach { item ->
                sb.append("${item.key}:${item.value.description}\n")
            }
            log(tag, "init admob:$sb")
        }
        getAAID()
    }


    override fun showRewarded(activity: Activity, callback: (Boolean) -> Unit) {
        log(tag, "showRewarded")
        val adRequest: AdRequest = AdRequest.Builder().build()
        RewardedAd.load(application, GOOGLE_REWARD_ID, adRequest, object : RewardedAdLoadCallback() {
            override fun onAdFailedToLoad(p0: LoadAdError) {
                super.onAdFailedToLoad(p0)
                log(tag, "onAdFailedToLoad:${p0.code},${p0.message}")
                callback.invoke(false)
            }

            override fun onAdLoaded(rewardedAd: RewardedAd) {
                super.onAdLoaded(rewardedAd)
                log(tag, "onAdLoaded")
                rewardedAd.show(activity, object : OnUserEarnedRewardListener {
                    override fun onUserEarnedReward(p0: RewardItem) {
                        log(tag, "onUserEarnedReward,${p0.amount}")
                    }
                })
            }
        })
    }

    override fun showBanner(activity: Activity, callback: (Boolean) -> Unit) {
    }

    private fun getAAID() {
        ThreadQueue.execOnCache {
            try {
                val adInfo: AdvertisingIdClient.Info = AdvertisingIdClient.getAdvertisingIdInfo(application)
                log(tag, adInfo.id)
            } catch (ex: Exception) {
                ex.printStackTrace()
            }
        }
    }
}